﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Jack.DataScience.Data.Converters
{
   public static class ConvertFaceToHtmlString
    {
        #region 生成GUID

        /// <summary>
        ///     生成GUID
        /// </summary>
        /// <returns></returns>
        public static string GetNewGuid()
        {
            return Guid.NewGuid().ToString("N");
        }

        #endregion

        /// <summary>
        /// 获取来源ID
        /// </summary>
        /// <returns>token字符串</returns>
        public static string GetWxSource(string code)
        {
            var result = "";
            switch (code)
            {
                case "joingrade":
                    result = "511";//家长建档 source:511
                    break;
                case "joinorg":
                    result = "55";//园长二维码 source:55
                    break;
                case "orgbrif":
                    result = "56";//推广二维码扫码 source:56
                    break;
                case "gradeInquiry":
                    result = "7912";//问卷调查二维码 source:7912
                    break;
                default:
                    result = "51";//幼儿园
                    break;

            }
            return result;
        }
        public static string GetWxPage(string code)
        {
            var result = "";
            switch (code)
            {
                case "joingrade"://家长建档 source:511
                    result = "pages/joinorg/joingrade/index";
                    // result = "pages/index/index";
                    break;
                case "joinorg"://园长二维码扫码 source:55
                    result = "pages/joinorg/index";
                    break;
                case "orgbrif"://推广二维码扫码 source:56
                    result = "pages/brief/index";
                    break;
                case "gradeInquiry"://问卷调查二维码 source:7912
                    result = "pages/my/healthydev/list/index";
                    break;
                default:
                    result = "pages/index/index";
                    break;

            }
            return result;
        }



        #region 转换用户字输入的字符串为可正确显示的html

        /// <summary>
        ///     表情编码文字对应字典
        /// </summary>
        public static Dictionary<int, string> FaceDic = new Dictionary<int, string>
            {
                {1, "微笑"},
                {2, "嘻嘻"},
                {3, "哈哈"},
                {4, "爱你"},
                {5, "晕"},
                {6, "流泪"},
                {7, "馋嘴"},
                {8, "抓狂"},
                {9, "哼"},
                {10, "可爱"},
                {11, "怒"},
                {12, "汗"},
                {13, "困"},
                {14, "害羞"},
                {15, "睡觉"},
                {16, "钱"},
                {17, "偷笑"},
                {18, "酷"},
                {19, "衰"},
                {20, "吃惊"},
                {21, "闭嘴"},
                {22, "鄙视"},
                {23, "挖鼻屎"},
                {24, "花心"},
                {25, "坏笑"},
                {26, "鼓掌"},
                {27, "失望"},
                {28, "思考"},
                {29, "生病"},
                {30, "亲亲"},
                {31, "抱抱"},
                {32, "怒骂"},
                {33, "太开心"},
                {34, "懒得理你"},
                {35, "右哼哼"},
                {36, "左哼哼"},
                {37, "嘘"},
                {38, "委屈"},
                {39, "吐"},
                {40, "可怜"},
                {41, "打哈气"},
                {42, "顶"},
                {43, "疑问"},
                {44, "做鬼脸"},
                {45, "搞怪"},
                {46, "握手"},
                {47, "耶"},
                {48, "good"},
                {49, "弱"},
                {50, "no"},
                {51, "ok"},
                {52, "赞"},
                {53, "来"},
                {54, "蛋糕"},
                {55, "心"},
                {56, "伤心"},
                {57, "钟"},
                {58, "猪头"},
                {59, "咖啡"},
                {60, "饭"},
                {61, "浮云"},
                {62, "飘过"},
                {63, "月亮"},
                {64, "太阳"},
                {65, "下雨"},
                {66, "遛狗"},
                {67, "灰机"},
                {68, "叶子"},
                {69, "花"},
                {70, "干杯"},
                {71, "求围观"},
                {72, "又胖啦"}
            };

        public static string ConvertToHtmlString(string source)
        {
            return ConvertToHtmlString(source, false);
        }

        /// <summary>
        ///     转换&为&amp;
        ///     空格为&nbsp;
        ///     <为& lt;>为&gt;
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="keepBR">是否保留换行</param>
        /// <returns></returns>
        public static string ConvertToHtmlString(string source, bool keepBR)
        {
            return source.Replace("&", "&amp;")
                         .Replace(" ", "&nbsp;")
                         .Replace("<", "&lt;")
                         .Replace(">", "&gt;")
                         .Replace("\r\n", keepBR ? "<br />" : "&nbsp;")
                         .Replace("\n", keepBR ? "<br />" : "&nbsp;");
        }

        public static string ParseHtmlString(string source)
        {
            return source.Replace("&amp;", "&")
                         .Replace("&nbsp;", " ")
                         .Replace("&lt;", "<")
                         .Replace("&gt;", ">")
                         .Replace("&mdash;", "—");
        }

  
        #endregion

        #region 字符串操作

        /// <summary>
        ///     搜索移除特殊字符
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RemoveSpecialCharacters(string source)
        {
            var regex = new Regex("[&|<|>|(\\\\r\\\\n)|(\\\\n)|(\\\\)|'|\\s]");
            return regex.Replace(source, "");
        }

        /// <summary>
        ///     截取字符串，中文算两个字符
        /// </summary>
        /// <param name="s">源字符串</param>
        /// <param name="bytes">截取长度</param>
        /// <returns></returns>
        public static string SubStrByByte(string s, int bytes)
        {
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            int totalBytes = 0;
            string res = "";
            for (int i = 0; i < s.Length; i++)
            {
                if (IsChinese(s[i]))
                {
                    totalBytes = totalBytes + 2;
                }
                else
                {
                    totalBytes = totalBytes + 1;
                }

                if (totalBytes <= bytes)
                {
                    res += s[i];
                }
                else
                {
                    break;
                }
            }
            return res;
        }

        public static int EngLength(string str)
        {
            var n = new ASCIIEncoding();

            byte[] b = n.GetBytes(str);
            int length = 0;
            for (int i = 0; i <= b.Length - 1; i++)
            {
                if (b[i] == 63)
                {
                    length++;
                }
                length++;
            }
            return length;
        }

        public static string SubString(string stringToSub, int length)
        {
            var regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            var sb = new StringBuilder();
            int nLength = 0;

            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    nLength += 3;
                }
                else
                {
                    nLength = nLength + 1;
                }

                if (nLength <= length)
                {
                    sb.Append(stringChar[i]);
                }
                else
                {
                    break;
                }
            }

            return sb.ToString();
        }

        public static string ClearHtmlTag(string html, int length = 0)
        {
            string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
            strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }
        /// <summary>
        ///     判断一个字符是否为中文字符
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsChinese(char c)
        {
            return c >= 0x4E00 && c <= 0x9FA5;
        }

        /// <summary>
        ///     获取大写的MD5签名结果
        /// </summary>
        /// <param name="encypStr"></param>
        /// <returns></returns>
        public static string GetMD5(string encypStr, string key)
        {
            encypStr += key;
            string retStr;
            var m5 = new MD5CryptoServiceProvider();

            //创建md5对象
            byte[] inputBye;
            byte[] outputBye;

            //使用GB2312编码方式把字符串转化为字节数组．
            inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);

            outputBye = m5.ComputeHash(inputBye);

            retStr = BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }

        public static string GetMD5(string encypStr)
        {
            return GetMD5(encypStr, "");
        }

  

        /// <summary>
        ///     检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {
            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        ///     检测是否有危险的可能用于链接的字符串
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeUserInfoString(string str)
        {
            return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest");
        }

        /// <summary>
        ///     将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }

        /// <summary>
        ///     通过用户的生日月份和日期，返回其星座名称
        /// </summary>
        /// <param name="month"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public static string GetZodiacName(int month, int day)
        {
            return
                ("摩羯,水瓶,双鱼,白羊,金牛,双子,巨蟹,狮子,处女,天秤,天蝎,射手,摩羯").Split(',')[
                    day < (20 + int.Parse(("2101122344432")[month].ToString())) ? month - 1 : month] + "座";
        }

        public static double MathRound(double dou, int num)
        {
            return Math.Round(dou, num);
        }

        public static double MathRound(double? dou)
        {
            if (dou != null)
                return MathRound(dou);
            else
                return 0;
        }

        /// <summary>
        ///     价格保留2位小数，"分"四舍五入
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        public static string FormatPrice(decimal price)
        {
            return Math.Round(price, 1).ToString("#0.00");
        }


        /// <summary>
        ///     转成html
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string FormatToHtml(string content)
        {
            content = content.Replace("\\r", "<br>");
            content = content.Replace("\r", "<br>");
            content = content.Replace("\\n", "<br>");
            content = content.Replace("\n", "<br>");
            content = content.Replace("\\t", "&nbsp;");
            content = content.Replace("\t", "&nbsp;");
            return content;
        }

        #endregion

      

        #region ip相关

        /// <summary>
        ///     是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

      
        #endregion

        #region email相关

        /// <summary>
        ///     检测是否符合email格式
        /// </summary>
        /// <param name="strEmail">要判断的email字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsValidEmail(string strEmail)
        {
            //return Regex.IsMatch(strEmail, @"^[A-Za-z0-9-_]+@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
            return Regex.IsMatch(strEmail, @"^[\w\.]+@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
        }

        public static bool IsValidDoEmail(string strEmail)
        {
            return Regex.IsMatch(strEmail,
                                 @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }

        #endregion

   
        #region 解析html中的图片的src
        /// <summary>   
        /// 取得HTML中所有图片的 URL。   
        /// </summary>   
        /// <param name="sHtmlText">HTML代码</param>   
        /// <returns>图片的URL列表</returns>   
        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签   
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串   
            MatchCollection matches = regImg.Matches(sHtmlText);
            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表   
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;
            return sUrlList;
        }
        #endregion

        
    }
}
